<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium">
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" @click="search">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="itemCode"
        label="任务编码"
        min-width="140">
      </el-table-column>
      <el-table-column
        prop="carEnterpriseName"
        label="车企"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="name"
        label="产品名称"
        min-width="120">
        <!-- <template scope="scope">

          {{nameModel(scope.row.name,scope.row.model)}}
        </template> -->
      </el-table-column>

      <el-table-column
        prop="model"
        label="产品型号"
        min-width="120">
        <!-- <template scope="scope">

          {{nameModel(scope.row.name,scope.row.model)}}
        </template> -->
      </el-table-column>
      <el-table-column
        prop="productTypeName"
        label="申报类型"
        min-width="150">
        <template scope="scope">
          {{scope.row.productTypeName1+"/"+scope.row.productTypeName2}}
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="testItems"
        label="检测项目"
        min-width="170">
        <template scope="scope">
          <span v-html="parseTestItem2(scope.row)"></span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        prop="siteName"
        label="场地"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="orgName"
        label="检测机构"
        min-width="120">
      </el-table-column> -->

      <el-table-column
        prop="currentStep"
        label="当前任务步骤"
        min-width="120">
        <template scope="scope">
          {{getDoneTitles(scope.row.currentStep)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="rollbackStep"
        label="回退步骤"
        min-width="120">
        <template scope="scope">
          {{getDoneTitlesIf(scope.row.rollbackStep,scope.row.taskStatus)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="rollbackName"
        label="回退用户"
        min-width="120">
        <template scope="scope">
          {{getRollbackNameIf(scope.row.rollbackName,scope.row.taskStatus)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="id"
        label="任务状态"
        min-width="120">
        <template scope="scope">
          <span v-if="scope.row.taskStatus == 1">已完成</span>
          <span v-if="scope.row.taskStatus == 2">进行中</span>
          <span v-if="scope.row.taskStatus == 3">回退(原因:{{scope.row.msg}})</span>
          <span v-if="scope.row.taskStatus == 4">转交</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="historyName"
        label="前一步完成用户"
        min-width="120">
      </el-table-column>
      <!-- <el-table-column
        prop="test"
        label="实验状态"
        min-width="120">
        <template scope="scope">
          <span v-if="scope.row.test == 1">未实验</span>
          <span v-if="scope.row.test == 2">实验中</span>
          <span v-if="scope.row.test == 3">实验完成</span>
        </template>
      </el-table-column> -->
      <el-table-column
        prop="suggestTime"
        label="建议完成时间"
        min-width="120">
        <template scope="scope">
          {{fmtDate(scope.row.suggestTime)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="importance"
        label="是否重要车型"
        min-width="120">
        <template scope="scope">
          {{significance(scope.row.importance)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="cause"
        label="原因"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="最后修改时间"
        min-width="160">
        <template scope="scope">
          {{fmtDate(scope.row.updateTime)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="nickname"

        label="创建人"
        min-width="160">
      </el-table-column>
      <el-table-column
        prop="note"
        label="备注"
        min-width="160">
      </el-table-column>
      <el-table-column
        fixed="right"
        prop="address"
        label="操作"
        min-width="260">
        <template slot-scope="scope">

          <template >
            <el-button size="mini" type="primary" @click="handlePVTask(scope.$index, scope.row)">子任务</el-button>
          </template>
          <template v-if="scope.row.currentStep=='a' || scope.row.currentStep=='c' || scope.row.currentStep=='d' || scope.row.currentStep=='e' || scope.row.currentStep=='f' || scope.row.currentStep=='g'">
            <el-button size="mini" type="primary" @click="handleTaskDone(scope.$index, scope.row)">处理</el-button>
          </template>
          <template v-else>
            <el-button size="mini" type="primary" @click="handleListTaskDone(scope.$index, scope.row)">下一步</el-button>
          </template>
          <template >
            <el-button size="mini" type="primary" @click="handleTaskBack(scope.$index, scope.row)">回退</el-button>
          </template>
          <el-button size="mini" type="primary" style="margin-top:8px" @click="handleTaskChangeUser(scope.$index, scope.row)">转交</el-button>
          <el-button size="mini" type="primary" @click="handleTaskDones(scope.$index, scope.row)">实验任务跟踪</el-button>
          <el-button size="mini" type="primary" style="margin-top:8px"@click="downloadByBlob(scope.row.url)">下载全部回退附件</el-button>
        </template>




      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog title="转交" :visible.sync="changeUserFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="changeUserForm" ref="changeUserForm" >
        <el-form-item label="用户" label-width="100px">
          <el-select v-model="changeUserForm.userId" placeholder="请选择" style="width: 90%;" >
            <el-option
              v-for="item in zjUserList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeUserFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitChangeUser">转交</el-button>
      </div>
    </el-dialog>

  <el-dialog title="回退" :visible.sync="backFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="backForm" ref="backForm" >
        <el-form-item label="回退步骤" label-width="100px">
          <el-select v-model="backForm.backStep" placeholder="请选择" style="width: 90%;" >
            <el-option
              v-for="item in backStepList"
              :key="item.key"
              :label="item.label"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原因" label-width="100px">
          <el-input v-model="backForm.msg" placeholder="请输入原因"></el-input>
        </el-form-item>
        <el-form-item label="上传附件" label-width="100px">
        <el-upload
          class="avatar-uploader"
          :action="uploadActionUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"

          multiple
          :on-success="handleAvatarSuccess"
          :file-list="fileList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div> -->
        </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="backFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitBack">回退</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="getDoneTitle()" :visible.sync="doneFormVisible" width="700px" :close-on-click-modal="false">
      <el-form :model="backForm" ref="backForm" >
        <el-row>
          <el-col :span="24">
            <table class="test-item-table">
              <tr>
                <th>项目代号</th>
                <th>检测项目</th>
                <th>数量</th>
                <th v-if="!onlyNext">
                  是否完成
                  <el-button type="primary" size="mini" plain @click.native.prevent="itemSelectAll">全选</el-button>
                </th>
              </tr>

              <tr v-for="(item,index) in taskItems">
                <td>{{item.serialNumber}}</td>
                <td>{{item.itemName}}</td>
                <td>{{item.num}}</td>
                <td v-if="!onlyNext">
                  <input v-model="doneForm.doneTaskItemIds" type="checkbox" :value="item.id" />
                </td>
              </tr>

            </table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button @click="doneFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitDoneSave" v-if="!onlyNext">保存</el-button>
        <el-button type="primary" @click.native.prevent="submitDoneNext">{{isLastStep()?"完成":'提交下一步'}}</el-button>
      </div>
    </el-dialog>




    <el-dialog title="关联任务" :visible.sync="doneFormVisibles" width="700px" :close-on-click-modal="false">

        <el-row>
          <el-col :span="24">
            <table class="test-item-table">
              <tr>
                <th>申报类型</th>
                <th>项目代号</th>
                <th>检测项目</th>
                <th>数量</th>
                <th>检测机构</th>
                <th>
                  是否完成
                  <!-- <el-button type="primary" size="mini" ></el-button> -->
                </th>
              </tr>

              <tr v-for="(item,index) in taskItems">
                <td>{{item.name +'/'+item.name1}}</td>
                <td>{{item.serialNumber}}</td>
                <td>{{item.itemName}}</td>
                <td>{{item.num}}</td>
                <td>{{item.orgName}}</td>
                <td>
                  <input v-model="doneForm.doneTaskItemIds" type="checkbox" :value="item.id" disabled="disabled">
                </td>
              </tr>

            </table>
          </el-col>
        </el-row>

      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button @click="doneFormVisibles = false">取 消</el-button>
        <!-- <el-button type="primary" @click.native.prevent="submitDoneSave">保存</el-button>
        <el-button type="primary" @click.native.prevent="submitDoneNext">提交</el-button> -->
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '../../../common/utils/util.js'
import {getToken} from '../../../common/utils/auth.js'
import {getMyTaskList, changeUser, back, getTaskItemsAndLogsTid, done} from '../../../api/test_order_task.js'
// import {getMyTaskList, taskSaveOrNext} from "../../../api/test_order.js";
// import {getAllTestCarEnterpriseList} from "../../../api/test_car_enterprise.js"
// import {getTestCarListByEntId} from "../../../api/test_car.js"
// import {getAllCarTypeList} from '../../../api/car_type.js'
// import {getAllTestProductTypeList} from '../../../api/test_product_type.js'
// import {getAllTestGroupListByParam} from '../../../api/test_group.js'
// import {getAllTestSiteList} from '../../../api/test_site.js'
import {getAllUserList} from '../../../api/user.js'
import {getTaskItemsCarAndLogsId} from "../../../api/test_order.js";
// import {getAllTestOrgList} from '../../../api/test_org.js'

/*

*/

export default {
  name: "myTaskManage",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      fileList:[],
      loadingDiv: null,
      uploadActionUrl:'',
      searchForm: {
      },


      doneFormVisible:false,
      doneFormVisibles:false,
      doneForm:{
        tid:'',
        doneTaskItemIds:[],
        currentStep:'',
        next: 0,
        fileList:[],
      },
      taskItems:[],
      doneTaskItems:[],
      doneRow: '',

      backFormVisible:false,
      backForm:{
        tid:'',
        msg:'',
        currentStep:'',
        backStep:'',
      },
      backStepList:[],

      changeUserFormVisible:false,
      changeUserForm:{
        tid:'',
        msg:'',
        userId:'',
        currentStep:'',
      },
      changeUserRow:{},

      userList: [],
    }
  },
  watch:{
    $route (to, from ) {
      // 监听路由变化, 实现类似 小程序的 onShow 事件
      if (to.path === '/task/test_order_manage') {
        if(this.nextShow){

        }
      }
    },

  },
  computed:{
    onlyNext(){
      if(this.doneForm.currentStep == 'a'
        || this.doneForm.currentStep == 'c'
        || this.doneForm.currentStep == 'e'
        || this.doneForm.currentStep == 'f'){
        return true;
      }
      return false;
    },
    userListAB(){
      if(util.isEmpty(this.userList)){
        return [];
      }

      let arr = [];
      // arr.push({id:0, nickname:'不适用'});
      for(let i in this.userList){
        if(this.userList[i].id == this.changeUserRow.c){
          continue;
        }
        arr.push(this.userList[i]);
      }

      return arr;
    },
    userListC(){
      if(util.isEmpty(this.userList)){
        return [];
      }

      let arr = [];
      for(let i in this.userList){
        if(this.userList[i].id == this.changeUserRow.a || this.userList[i].id == this.changeUserRow.b){
          continue;
        }
        arr.push(this.userList[i]);
      }

      return arr;
    },

    userListD(){
      if(util.isEmpty(this.userList)){
        return [];
      }

      let arr = [];
      for(let i in this.userList){
        if(this.userList[i].id == this.changeUserRow.e){
          continue;
        }
        arr.push(this.userList[i]);
      }

      return arr;
    },

    userListE(){
      if(util.isEmpty(this.userList)){
        return [];
      }

      let arr = [];
      for(let i in this.userList){
        if(this.userList[i].id == this.changeUserRow.d){
          continue;
        }
        arr.push(this.userList[i]);
      }

      return arr;
    },
    zjUserList(){
      if(this.changeUserForm.currentStep == 'a' || this.changeUserForm.currentStep == 'b'){
        return this.userListAB;
      }
      if(this.changeUserForm.currentStep == 'c'){
        return this.userListC;
      }
      if(this.changeUserForm.currentStep == 'd'){
        return this.userListD;
      }
      if(this.changeUserForm.currentStep == 'e'){
        return this.userListE;
      }

      return this.userList;
    }
  },
  created() {

  },
  mounted() {
    this.init();
    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }

    let t = getToken();
    this.uploadActionUrl = this.$adminApiUrl + "/file/upload?_t="+t;
    this.fileBaseUrl = this.$adminApiUrl+"/file/get?_t="+t+"&f=";
  },
  methods: {
    itemSelectAll(){
      let arr = [];

      for(let i in this.taskItems){
        arr.push(this.taskItems[i].id)
      }

      this.doneForm.doneTaskItemIds = arr;
    },

    handleRemove(file, fileList) {

      this.fileList = fileList;
      let data = [];
      // console.log(this.fileList.length)
      for(var i=0;i<this.fileList.length;i++){

        // console.log(fileList[i].response.data)
        data.push(fileList[i].response.data)
      }
      this.backForm.fileList = data;
      // this.editForm.fileList = fileList;

            // console.log(file, fileList);
      },

    handlePVTask(index, row){
      let item = {
        componentName:"testTaskPvManage",
        icon:"",
        path:"/task/test_task_pv_manage/"+row.tOrderId+'/'+row.currentStep,
        title: "子任务",
      };

      this.$store.commit("openTab",{item:item, router: (path)=>{this.$router.replace(path)}})

    },
    submitDoneSave(){
      this.doneForm.next = 0;
      this.submitDone();
    },

    submitDoneNext(){
      if(this.onlyNext){
        let arr = [];

        for(let i in this.taskItems){
          arr.push(this.taskItems[i].id)
        }

        this.doneForm.doneTaskItemIds = arr;
      }

      if(this.doneForm.doneTaskItemIds.length != this.taskItems.length){
        this.$message.error("请确认完成全部检测项目");
        return;
      }
      this.doneForm.next = 1;
      this.submitDone();
    },

    submitDone(){

      let title = "保存中"
      if(this.doneForm.next == 1){
        if(this.isLastStep()){
          title = "完成中"
        }else{
          title = "提交下一步中"
        }
      }

      const loadingDiv = util.showLoading(title)
      done(this.doneForm).then(res => {
        if(res.code == 0) {
          this.$alert(res.msg, "失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(()=> {
              this.doneFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    handleTaskDone(index, row){

      getTaskItemsAndLogsTid({tid: row.tOrderId, step: row.currentStep}).then(res=>{
        // console.log(res)
        if(res.code == 1){
          this.taskItems = res.data.taskItems;
          this.doneTaskItems = res.data.doneTaskItems;

          let arr = [];
          if(!util.isEmpty(this.doneTaskItems)){
            for(let i in this.doneTaskItems){
              arr.push(this.doneTaskItems[i].orderTaskItemId)
            }
          }
          this.doneForm.tid = row.tOrderId;
          this.doneForm.currentStep = row.currentStep;
          this.doneForm.doneTaskItemIds = arr;
          this.doneRow = row;

          this.doneFormVisible=true;
        }else{
          this.$message.error("加载信息失败")
        }
      });


    },

    handleTaskDones(index, row){

      getTaskItemsCarAndLogsId({tOrderId:row.tOrderId}).then(res=>{
        // console.log(res)
        if(res.code == 1){
          this.taskItems = res.data.taskItems;
          this.doneTaskItems = res.data.doneTaskItems;

          let arr = [];
          if(!util.isEmpty(this.doneTaskItems)){
            for(let i in this.doneTaskItems){
              arr.push(this.doneTaskItems[i].orderTaskItemCarId)
            }
          }
          this.doneForm.carId = row.id;
          this.doneForm.doneTaskItemIds = arr;
          this.doneRow = row;

          this.doneFormVisibles=true;
        }else{
          this.$message.error("加载信息失败")
        }
      });
    },


    handleListTaskDone(index, row){
      getTaskItemsAndLogsTid({tid: row.tOrderId, step: row.currentStep}).then(res=>{
        // console.log(res)
        if(res.code == 1){
          this.taskItems = res.data.taskItems;
          this.doneTaskItems = res.data.doneTaskItems;

          let arr = [];
          for(let i in this.taskItems){
            arr.push(this.taskItems[i].id)
          }

          this.doneForm.tid = row.tOrderId;
          this.doneForm.currentStep = row.currentStep;
          this.doneForm.doneTaskItemIds = arr;
          this.doneRow = row;

          this.submitDoneNext();

        }else{
          this.$message.error("加载信息失败")
        }
      });
    },

    getDoneTitle(){
      if(util.isEmpty(this.doneForm.currentStep)){
        return "";
      }

      switch(this.doneForm.currentStep){
        case "a":
          return "检测方案核定";
        case "b":
          return "参数填报";
        case "c":
          return "方案参数审核";
        case "d":
          return "报告出具";
        case "e":
          return "报告审核";
        case "f":
          return "批准";
        case "g":
          return "原始记录";
        case "h":
          return "提交检测机构";
        case "i":
          return "检测机构已提交";
        case "j":
          return "检测报告生成";
        case "k":
          return "企业提交";
        case "l":
          return "反馈";
        case "m":
          return "反馈提交";
        case "n":
          return "审核通过";
        case "o":
          return "客户确认";

      }
    },



    isLastStep(){
      //公告：ABCDEF 1
      // 达标：ABDEFCGHI 2
      // CCC：ABFC 3
      // 环保：ABF 4
      // 其他：ABFJ 19
      if(this.doneRow.productTypeId1 == 1 && this.doneForm.currentStep == 'k'){
        return true;
      }
      if(this.doneRow.productTypeId1 == 2 && this.doneForm.currentStep == 'n'){
        return true;
      }
      if(this.doneRow.productTypeId1 == 3 && this.doneForm.currentStep == 'g'){
        return true;
      }
      if(this.doneRow.productTypeId1 == 4 && this.doneForm.currentStep == 'k'){
        return true;
      }
      if(this.doneRow.productTypeId1 == 19 && this.doneForm.currentStep == 'o'){
        return true;
      }

      return false;
    },

    handleTaskBack(index, row){

      this.backForm.fileList = [];
      this.fileList = [];

      this.backForm.tid = row.tOrderId;
      this.backForm.msg = '';
      this.backForm.backStep = '';
      this.backForm.currentStep = row.currentStep;

      // 计算可以回退的步骤
      //公告：ABCDEF 1
      //达标：ABDEFCGHI 2
      //CCC：ABFC 3
      //环保：ABF 4
      //其他：ABFJ 19
      let steps = [];

      let a = row.productTypeId1-0;
      switch(a){
        case 1:
          steps=['a','b','c','d','e','f','g','h','i','k'];
          break;
        case 2:
          steps=['a','b','c','d','e','f','g','h','j','k','l','m','n'];
          break;
        case 3:
          steps=['a','b','c','d','e','f','k','g'];
          break;
        case 4:
          steps=['a','b','c','d','e','f','k'];
          break;
        case 19:
          steps=['a','b','c','d','e','f','k','o'];
          break;
      }

      let arr = [];
      // let currentStep = 'e';
      let currentStep = this.backForm.currentStep;

      if(currentStep == 'a' || currentStep == 'b' || currentStep == 'c'){

        arr.push({
          "key": "0",
          "label": "检测任务下单",
        });
      }

      for(let i in steps){
        if(steps[i] == currentStep){
          break;
        }
        arr.push({
          "key": steps[i],
          "label": this.getDoneTitles(steps[i]),
          // getDoneTitles
        });



      }
      // console.log(steps)
      // console.log(arr)
      // console.log(this.backStepList)
      this.backStepList = arr;
      this.backFormVisible = true;
    },
    submitBack(){
      if(util.isEmpty(this.backForm.backStep)){
        this.$message.error("请选择用户");
        return;
      }

      if(util.isEmpty(this.backForm.msg)){
        this.$message.error("请填写回退原因");
        return;
      }

      const loadingDiv = util.showLoading("回退中")
      back(this.backForm).then(res => {
        if(res.code == 0) {
          this.$alert(res.msg, "失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(()=> {
              this.backFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    getDoneTitles(data){
      switch(data){
        case "a":
          return "检测方案核定";
        case "b":
          return "参数填报";
        case "c":
          return "方案参数审核";
        case "d":
          return "报告出具";
        case "e":
          return "报告审核";
        case "f":
          return "批准";
        case "g":
          return "原始记录";
        case "h":
          return "提交检测机构";
        case "i":
          return "检测机构已提交";
        case "j":
          return "检测报告生成";
        case "k":
          return "企业提交";
        case "l":
          return "反馈";
        case "m":
          return "反馈提交";
        case "n":
          return "审核通过";
        case "o":
          return "客户确认";

      }
    },
    getRollbackNameIf(data,data1){
        if(data1==3){
          return data;
        }else{
          return '';
        }
    },

    getDoneTitlesIf(data,data1){
      if(data1==3){
        switch(data){
          case "a":
            return "检测方案核定";
          case "b":
            return "参数填报";
          case "c":
            return "方案参数审核";
          case "d":
            return "报告出具";
          case "e":
            return "报告审核";
          case "f":
            return "批准";
          case "g":
            return "原始记录";
          case "h":
            return "提交检测机构";
          case "i":
            return "检测机构已提交";
          case "j":
            return "检测报告生成";
          case "k":
            return "企业提交";
          case "l":
            return "反馈";
          case "m":
            return "反馈提交";
          case "n":
            return "审核通过";
          case "o":
            return "客户确认";

        }
      }else{
        return '';
      }

    },


    handleTaskChangeUser(index, row){
      this.changeUserForm.tid = row.tOrderId;
      this.changeUserForm.msg = '';
      this.changeUserForm.userId = '';
      this.changeUserForm.currentStep = row.currentStep;
      this.changeUserRow = row;

      this.changeUserFormVisible = true;
    },
    submitChangeUser(){

      if(util.isEmpty(this.changeUserForm.userId)){
        this.$message.error("请选择用户");
        return;
      }

      const loadingDiv = util.showLoading("转交中")
      changeUser(this.changeUserForm).then(res => {
        if(res.code == 0) {
          this.$alert(res.msg, "失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(()=> {
              this.changeUserFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },


    handlePreview(file) {
            // console.log(file);
          },




    downloadByBlob(url) {
      if(util.isEmpty(url)){
        this.$message.error("未发现文件");
        return;
      }
      let urlArr = url.split(",");
      for(var i =0;i<urlArr.length;i++){

        url = this.fileBaseUrl+urlArr.[i]
        // console.log(url)
        this.download(url,i)
        // 用完释放URL对象


      }

      // let urlArr = url.split(",");
      // for(var i =0;i<urlArr.length;i++){
      //   console.log("123")
      //   let image = new Image()
      //   image.setAttribute('crossOrigin', 'anonymous')
      //   image.src = this.fileBaseUrl+urlArr.[i]
      //   console.log(image.src)
      //   // window.open(image.src)
      //   image.onload = () => {
      //   let canvas = document.createElement('canvas')
      //   canvas.width = image.width
      //   canvas.height = image.height
      //   let ctx = canvas.getContext('2d')
      //   ctx.drawImage(image, 0, 0, image.width, image.height)
      //   canvas.toBlob((blob) => {
      //   let url = URL.createObjectURL(blob)
      //   this.download(image.src,i)
      //   // 用完释放URL对象
      //   URL.revokeObjectURL(url)
      //       })
      //     }
      // }

      },

      download(urls,i)
      {undefined
      fetch(urls).then((res) => {undefined
                          res.blob().then((blob) => {undefined
                              const url = window.URL.createObjectURL(blob)
                              const a = document.createElement('a')
                              a.href = url
                              a.download = i ;
                              a.click()
                              window.URL.revokeObjectURL(url)
                          })
                      })
                  },


      // download(href, name) {
      // let eleLink = document.createElement('a')
      // eleLink.download = name
      // eleLink.href = href
      // eleLink.click()
      // eleLink.remove()
      // },
    // beforeRemove(file, fileList) {
    //     return this.$confirm(`确定移除 ${ file.name }？`);
    //   },




    init(){
    //   getAllTestCarEnterpriseList().then(res => {
    //     if(res.code == 1) {
    //       this.carEntList = res.data;
    //     }
    //   }).catch(res => {

    //   })
    //   this.getAllCarTypeList();

      // 获取所有检测产品类别
    //   getAllTestProductTypeList().then(res => {
    //     if(res.code == 1) {
    //       this.testProductTypeList = res.data;
    //     }
    //   }).catch(res => {

    //   });

      // 获取所有检测场地
    //   getAllTestSiteList().then(res => {
    //     if(res.code == 1) {
    //       this.testSiteList = res.data;
    //     }
    //   }).catch(res => {

    //   });

      // 获取所有用户列表
      getAllUserList().then(res => {
        if(res.code == 1) {
          this.userList = res.data;
        }
      }).catch(res => {

      });

    //   getAllTestOrgList().then(res => {
    //     if(res.code == 1) {
    //       this.orgList = res.data;
    //     }
    //   }).catch(res => {

    //   });

    },
    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2), fmt);
    },
    significance(data){
      if(data==1){
        return "是";
      }else{
        return "否";
      }
    },

    handleAvatarSuccess(res, file, fileList){
      // console.log("12")
      // this.avatarUploadLoadingDiv.close();
      if (res.code == 1){
        this.fileList = fileList;
        let data = [];
        // console.log(this.fileList.length)
        for(var i=0;i<this.fileList.length;i++){

          // console.log(fileList[i].response.data)
          if(fileList[i].response!=null&&fileList[i].response!=''){
            data.push(fileList[i].response.data)
          }
        }
        this.backForm.fileList = data;
        // console.log(this.editForm.fileList)
        // this.fileList = fileList;
        // console.log("++++++++++++++++++");
        // console.log(this.editForm.fileList);
        // console.log(this.res.data);
        // console.log("++++++++++++++++++");
        return;
      }else{
        this.$message({
          message: res.msg,
          type: 'warning'
        });
      }
    },

    submitForm() {
      this.editForm.next = 0;
      this.taskSaveOrNext();
    },
    submitFormNext() {
      this.editForm.next = 1;
      this.taskSaveOrNext();
    },

    getDataWithType(dataList, type){
      for(let i in dataList){
        if(dataList[i].type == type){
          return dataList[i];
        }
      }
    },

    taskSaveOrNext(){


      // this.$refs.editForm.validate(valid => {
        // if(valid) {
          this.loading = true;
          let loadingText = "暂存中...";
          if(this.editForm.next == 1){
            loadingText = "下一步中...";
            if(this.editForm.step==4){
              loadingText = "完成中...";
            }
          }
          const loadingDiv = util.showLoading(loadingText)
          taskSaveOrNext(this.editForm).then(res => {
            let title = "暂存"
            if(this.editForm.next == 1){
              title = "下一步"
              if(this.editForm.step==4){
                title = "完成"
              }
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage);
                  if(this.editForm.step==2){
                    this.step2EditFormVisible=false;
                  }else if(this.editForm.step==3){
                    this.step3EditFormVisible=false;
                  }else if(this.editForm.step==4){
                    this.step4EditFormVisible=false;
                  }
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        // }
      // });
    },

    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestOrder({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage);

            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      let param = {};
      for(let key in this.searchForm){
        param[key] = this.searchForm[key];
      }
      param['pageSize'] = this.pageSize;
      param['pageNum'] = pageNum;

      getMyTaskList(param).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
  .test-item-table{
    width: 80%;
    border-collapse: collapse;

    th, td {
      width: 33.3%;
      text-align: center;
      border: 1px solid #CCC;
    }
  }

  .test-item-table{
    width: 100%;
    border-collapse: collapse;
    tr{
      height: 40px;
    }

    th, td {
      width: 7%;
      text-align: center;
      border: 1px solid #CCC;
    }
    th {
      background-color: #EDF2FC;
    }
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
